package starComponent.elements;

import java.awt.Point;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;


/**
 * @author Charles Perin
 * 15 avr. 2011
 * LIMSI - INRIA Rennes
 * charles.perin@free.fr
 */
public class PastTrace {

	/**
	 * le temps de conservation des valeurs passees, en millisecondes
	 */
	private int timeTrace = 5000;

	/**
	 * l'etoile associee
	 */
	private StarComponent star;

	/**
	 * la frequence de sauvegarde des donnees
	 */
	private long frequency = 5;

	/**
	 * la hashmap associant a chaque branche sa liste de valeurs passees
	 */
	private HashMap<A_StarBranch, LinkedList<Point>> valuesMap = new HashMap<A_StarBranch, LinkedList<Point>>(); 

	/**
	 * le timer de la classe 
	 */
	private Timer timer;

	public PastTrace(StarComponent star){
		this.star = star;
		if(star.getControler().isPastTrace())startRemember();
	}

	public void startRemember(){
		timer = new Timer();
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				saveAllBranchesValues();
				star.repaint();
			}
		};
		timer.scheduleAtFixedRate(timerTask, 0, frequency);
	}
	
	public void stopRemember(){
		if(timer!=null)timer.cancel();
	}

	public void createValuesMap(){
		for(A_StarBranch b:star.getControler().getDisplayedBranchlist()){
			LinkedList<Point> branchValues = new LinkedList<Point>();
			valuesMap.put(b, branchValues);
		}
	}

	private void saveAllBranchesValues() {
		HashMap<A_StarBranch, LinkedList<Point>> safeMap = new HashMap<A_StarBranch, LinkedList<Point>>(valuesMap);
		synchronized (safeMap) {
			Iterator<A_StarBranch> iter = safeMap.keySet().iterator();
			while(iter.hasNext()){
				A_StarBranch branch = iter.next();
				LinkedList<Point> branchList = safeMap.get(branch);
				if(branch instanceof StarBranchSlider){
					branchList.addFirst(((StarBranchSlider)branch).getThumb().getCenter());
				}
				else if(branch instanceof StarBranchBiSlider){
					branchList.addFirst(((StarBranchBiSlider)branch).getMiddle());
				}
				if(branchList.size()>timeTrace/frequency){
					branchList.removeLast();
				}
			}
		}
		valuesMap = new HashMap<A_StarBranch, LinkedList<Point>>(safeMap);
	}


	public void setTimeTrace(int timeTrace) {
		this.timeTrace = timeTrace;
	}

	public int getTimeTrace() {
		return timeTrace;
	}
	
	
	public HashMap<A_StarBranch, LinkedList<Point>> getValuesMap() {
		return valuesMap;
	}

	public void setValuesMap(HashMap<A_StarBranch, LinkedList<Point>> valuesMap) {
		this.valuesMap = valuesMap;
	}

	public long getFrequency() {
		return frequency;
	}

	public void setFrequency(long frequency) {
		this.frequency = frequency;
	}
}
